<template>
  <div class="publicity-detail-view view-container">

    <header-module left-custom padding>
      <template #left-con>
        <div>
          <span style="font-size: 16px; margin-right: 20px" v-if="datas.planInfo.planType == 1">精细招商规划</span>
          <span style="font-size: 16px; margin-right: 20px" v-else-if="datas.planInfo.planType == 2">区域招商规划</span>
          <span style="font-size: 16px; margin-right: 20px" v-else-if="datas.planInfo.planType == 3">终端直销规划</span>
          <span style="font-size: 16px; margin-right: 20px" v-else-if="datas.planInfo.planType == 4">商业营销规划</span>

          <el-tag size="small" type="warning">{{ getStatus() }}</el-tag>

        </div>
      </template>
      {{ datas.planDetail.detailStatus }}
      <template #btn>
        <el-button class="main-btn" size="small" @click="onBack">返回</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="onEditorial" v-if="datas.planInfo.planType == 2 || datas.planInfo.planType == 1">推荐代理</el-button>
        <el-button
            v-if="(datas.planDetail.detailStatus == 0 || datas.planDetail.detailStatus == -3 || datas.planDetail.detailStatus == -4 || datas.planDetail.detailStatus == -5)
&& datas.planInfo.planType == 2 || datas.planInfo.planType == 1"
            class="main-btn" size="small" type="primary" @click="onAgent">检索代理库
        </el-button>
        <el-button v-if="datas.planDetail.detailStatus == -2 && userInfo.ID == datas.allocationAgent?.headId"
                   class="main-btn" size="small" type="primary" @click="onAccepted">接受
        </el-button>
        <el-button v-if="datas.planDetail.detailStatus == -2 && userInfo.ID == datas.allocationAgent?.headId"
                   class="main-btn" size="small" type="primary" @click="onReject">拒绝
        </el-button>
        <!--        <el-button v-if="datas.planDetail.detailStatus == 1 && userInfo.ID == datas.allocationAgent?.headId" class="main-btn" size="small" type="primary" @click="addAgreement">代理协议签约</el-button>-->
        <!--        <el-button v-if="datas.planDetail.detailStatus == 1 && userInfo.ID == datas.allocationAgent?.headId && datas.planDetail.planType == 1" class="main-btn" size="small" type="primary" @click="onTerminal">注册终端</el-button>-->
        <!--        <el-button v-if="(datas.planDetail.detailStatus == 2 || datas.planDetail.detailStatus == 3) && userInfo.ID == datas.allocationAgent?.headId && datas.planDetail.planType == 1" class="main-btn" size="small" type="primary" @click="handlSet">设置配送信息</el-button>-->
        <!--        <el-button v-if="datas.planDetail.detailStatus >= 2 && userInfo.ID == datas.allocationAgent?.headId && datas.planDetail.planType == 1" class="main-btn" size="small" type="primary" @click="handlFailure">终端开发失败</el-button>-->

        <template v-if="datas.planDetail.id">
          <el-button
              v-auth="{v:['crm:marketing:planFine:allocation'],bool:(datas.planDetail.detailStatus == 0 || datas.planDetail.detailStatus == -3 || datas.planDetail.detailStatus == -4 || datas.planDetail.detailStatus == -5) && datas.planDetail.planType == 1}"
              lass="main-btn" size="small" type="primary" @click="onAllocation(row)">分配
          </el-button>
          <el-button
              v-auth="{v:['crm:marketing:planSigned:allocation'],bool:(datas.planDetail.detailStatus == 0 || datas.planDetail.detailStatus == -3 || datas.planDetail.detailStatus == -4 || datas.planDetail.detailStatus == -5) && datas.planDetail.planType == 2}"
              lass="main-btn" size="small" type="primary" @click="onAllocation(row)">分配
          </el-button>
          <el-button
                  v-auth="{v:['crm:marketing:planDirect:allocation'],bool:(datas.planDetail.detailStatus == 0 || datas.planDetail.detailStatus == -3 || datas.planDetail.detailStatus == -4 || datas.planDetail.detailStatus == -5) && datas.planDetail.planType == 3}"
                  lass="main-btn" size="small" type="primary" @click="onAllocation1(row)">分配
          </el-button>
          <el-button
                  v-auth="{v:['crm:marketing:planBusiness:allocation'],bool:(datas.planDetail.detailStatus == 0 || datas.planDetail.detailStatus == -3 || datas.planDetail.detailStatus == -4 || datas.planDetail.detailStatus == -5) && datas.planDetail.planType == 4}"
                  lass="main-btn" size="small" type="primary" @click="onAllocation2(row)">分配
          </el-button>
        </template>

      </template>

    </header-module>

    <div class="main-content">

      <signedDetail v-if="datas.planInfo.planType == 2" :datas="datas"/>

      <fineDetail v-else-if="datas.planInfo.planType == 1" :datas="datas"/>

      <directDetail v-else-if="datas.planInfo.planType == 3" :datas="datas"/>

      <businessDetail v-else-if="datas.planInfo.planType == 4" :datas="datas"/>

    </div>

    <detail-drawer
        ref="detailDrawer"
        :size-width="1000"
        custom-title
    >
      <template #title>
        <span>检索代理库</span>
      </template>
      <template #contents>

        <agentLibrary :datas="libraryData"/>

      </template>
    </detail-drawer>

    <addAgreementDialog ref="agreementDialog"/>

    <allocationDialog ref="allocationDialog" @success="getData"/>

    <registered ref="registeredDialog" @succsessReg="getData"/>

    <!--设置配送信息-->
    <setiDelivery ref="setiDeliveryDialog" @distributeSuccsess="getData"/>

    <rejectDialog ref="rejectDialog" @success="getData"/>

    <altDirectDialog ref="altDirectDialog" @success="getData"/>

    <altBusinessDialog ref="altBusinessDialog" @success="getData"/>

  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {useRoute, useRouter} from 'vue-router'
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs} from 'vue'

export default defineComponent({
  name: 'Index',
  components: {
    altBusinessDialog : defineAsyncComponent(
            () => import('../list/modules/altBusinessDialog.vue')
    ),
    altDirectDialog : defineAsyncComponent(
            () => import('../list/modules/altDirectDialog.vue')
    ),
    businessDetail : defineAsyncComponent(
            () => import('../../../planManagement/plan/detail/modules/businessDetail.vue')
    ),
    directDetail : defineAsyncComponent(
            () => import('../../../planManagement/plan/detail/modules/directDetail.vue')
    ),
    rejectDialog: defineAsyncComponent(
        () => import('../list/modules/rejectDialog.vue')
    ),
    signedDetail: defineAsyncComponent(() =>
        import('../../../planManagement/plan/detail/modules/signedDetail.vue')
    ),
    fineDetail: defineAsyncComponent(() =>
        import('../../../planManagement/plan/detail/modules/fineDetail.vue')
    ),
    agentLibrary: defineAsyncComponent(() =>
        import('./modules/agentLibrary.vue')
    ),
    addAgreementDialog: defineAsyncComponent(() =>
        import('../../modules/addAgreementDialog.vue')
    ),
    allocationDialog: defineAsyncComponent(() =>
        import('../list/modules/allocationDialog.vue')
    ),
    registered: defineAsyncComponent(() =>
        import('../../customer/terminal/modules/registered.vue')
    ),
    setiDelivery: defineAsyncComponent(() =>
        import('../../customer/terminal/modules/setiDelivery.vue')
    ),
  },
  computed: {
    ...mapGetters('user', ['userInfo']),
  },
  setup() {
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const route = useRoute()
    const router = useRouter()
    var data = reactive({
      datas: {
        planDetail: {},
        planInfo:{}
      },
      detailDrawer: null,
      libraryData: {
        agentType: '',
        productId: 0,
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        terminalId: 0,
        from: '1'
      },
      agreementDialog: null,
      allocationDialog: null,
      registeredDialog: null,
      setiDeliveryDialog: null,
      rejectDialog: null,
      altDirectDialog:null,
      altBusinessDialog:null,
    })

    const onBack = () => {
      router.back()
    }

    const onAgent = () => {
      data.detailDrawer.open()
    }

    const addAgreement = () => {
      data.agreementDialog.open(data.datas.planDetail.planType == 1 ? 2 : 1, data.datas)
    }

    const getDevData = () => {
      return new Promise((resolve, reject) => {
        api.terminal.PRODUCT_DETAILS(data.datas.planDetail.devId).then((res) => {
          if (res.code === 0) {
            resolve(res.data)
          } else {
            reject(res.msg)
          }
        })
      })
    }

    const onEditorial = () => {
      router.push({path: '/editorial/agent/create', query: {id: data.datas.planDetail.id}})
    }

    const onTerminal = () => {
      getDevData().then(res => {
        data.registeredDialog.open(res, null, 1, false)
      })
    }

    // 设置配送信息
    const handlSet = () => {
      getDevData().then(res => {
        data.setiDeliveryDialog.open(res, data.datas.planDetail.devId)
      })
    }

    const onAccepted = () => {
      currentInstance.proxy
          .alertBox({
            message: '确认同意接受此任务？',
            title: '接受',
          })
          .then(() => {
            api.plan.ALLOCATION_AGENT_DEAL({planDetailId: data.datas.planDetail.id, type: '1'}).then(res => {
              if (!res.code) {
                currentInstance.proxy.customMessage({type: 'success', message: '处理成功'})
                getData()
              } else {
                currentInstance.proxy.customMessage({type: 'error', message: res.msg})
              }
            })
          })
          .catch((err) => {
            console.log(err)
          })
    }

    const onReject = () => {
      data.rejectDialog.open(data.datas.planDetail.id)
    }

    const handlFailure = () => {
      currentInstance.proxy
          .alertBox({
            message: '确定更改此规划为开发失败？',
            title: '开发失败',
          })
          .then(() => {
            api.terminal.TERMINAL_FAILURE(data.datas.planDetail.devId).then((res) => {
              if (res.code) {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              } else {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '操作成功',
                })
                getData()
              }
            })
          })
          .catch((err) => {
            console.log(err)
          })
    }

    const getData = () => {
      api.plan.PLAN_DETAIL_DETAIL(route.query.id).then(res => {
        if (!res.code) {
          data.datas = res.data
          data.libraryData.productId = data.datas.planDetail.productId
          if (data.datas.planDetail.planType == 1) {
            data.libraryData.from = '2'
            data.libraryData.provinceCode = data.datas.planDetail.terminalProvince
            data.libraryData.cityCode = data.datas.planDetail.terminalCity
            data.libraryData.areaCode = data.datas.planDetail.terminalArea
            data.libraryData.terminalId = data.datas.planDetail.terminalId
          } else {
            data.libraryData.from = '1'
            data.libraryData.provinceCode = data.datas.planDetail.provinceCode
            data.libraryData.cityCode = data.datas.planDetail.cityCode
            data.libraryData.areaCode = data.datas.planDetail.areaCode
          }
        } else {
          currentInstance.proxy.customMessage({type: 'error', message: res.msg})
        }
      })
    }

    const onAllocation = () => {
      data.allocationDialog.open(data.datas)
    }

    const onAllocation1 = () => {
      data.altDirectDialog.open(data.datas)
    }

    const onAllocation2 = () => {
      data.altBusinessDialog.open(data.datas)
    }

    const getStatus = () => {
      let str = ''

      switch (data.datas.planDetail?.detailStatus) {
        case "0":
          str = '待分配';
          break;
        case "-2":
          str = '分配待确认';
          break;
        case "-3":
          str = '已拒绝';
          break;
        case "-4":
          str = '代理开发失败';
          break;
        case "-5":
          str = '终端开发失败';
          break;
        case "1":
          str = '已分配';
          break;
        case "2":
          str = '已分配';
          break;
        case "3":
          str = '已分配';
          break;
      }
      if (str == '终端开发中' && data.datas.planInfo.planType == 4){
        str = '客户开发中'
      }
      return str
    }

    onMounted(() => {
      getData()
    })

    return {
      ...toRefs(data),

      onBack,
      onAgent,
      addAgreement,
      getData,
      onAllocation,
      onTerminal,
      handlSet,
      handlFailure,
      onEditorial,
      getStatus,
      onAccepted,
      onReject,
      onAllocation1,
      onAllocation2,
    }
  }
})
</script>

<style scoped>

</style>
